package Gson;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class GsonClient {
	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		Gson gson = new Gson();
		Socket serverSocket = new Socket("localhost", 90);
    	JsonReader reader = new JsonReader(new InputStreamReader(serverSocket.getInputStream()));
    	JsonWriter writer = new JsonWriter(new OutputStreamWriter(serverSocket.getOutputStream()));
    	long time = System.currentTimeMillis();
    	for (int i = 0; i < 10000; i++) {
    		gson.toJson(SensorData.generate(), SensorData.class, writer);
    		writer.flush();
    		String end = gson.fromJson(reader, String.class);
    		while (!(end.equals("end"))) {
    			Thread.sleep(5);
    			end = gson.fromJson(reader, String.class);
    		}
    	}
    	System.out.println("throughput = "+1d * (System.currentTimeMillis() - time)/10000);
    	long timeDelay = System.currentTimeMillis();
    	gson.toJson(SensorData.generate(), SensorData.class, writer);
    	writer.flush();
		String end = gson.fromJson(reader, String.class);
		while (!(end.equals("end"))) {
			Thread.sleep(5);
    		end = gson.fromJson(reader, String.class);
		}
		System.out.println("delay = "+1d*(System.currentTimeMillis() - timeDelay));
		reader.close();
		writer.close();
    	serverSocket.close();
	}
}
